#!/usr/bin/php

<?php

$opt = getopt("r:");
$rel = isset($opt['r']) ? intval($opt['r']) : '1';

$arch = trim(shell_exec("arch"));

if ($arch != "x86_64") {
    die("The architecture of the operating system does not support: $arch");
}

$basedir = realpath(__DIR__.'/../..');

$pkgname = "lesskeeper";

$cmd = "
killall lesskeeper-store\n
cd $basedir/deps/redis\n
make\n
cp -rp ./src/redis-cli $basedir/bin/lesskeeper-cli 
cp -rp ./src/redis-server $basedir/bin/lesskeeper-store ";

shell_exec($cmd);

$ver = file_get_contents($basedir."/src/version.go");
if (!preg_match("/VERSION\ +string\ +\=\ +\"(.*)\"/", $ver, $mat)) {
    die("Can not get version");
}
$ver = $mat[1];

$cmd = "
rm -rf /tmp/rpm-tmp*
rm -rf /tmp/{BUILD,RPMS,SOURCES,SPECS,SRPMS,BUILDROOT}
mkdir -p /tmp/{BUILD,RPMS,SOURCES,SPECS,SRPMS,BUILDROOT}

rm -rf /tmp/SOURCES/lesskeeper*

mkdir -p /tmp/SOURCES/{$pkgname}-{$ver}/bin
mkdir -p /tmp/SOURCES/{$pkgname}-{$ver}/var
mkdir -p /tmp/SOURCES/{$pkgname}-{$ver}/etc


cp -rp $basedir/bin/lesskeeper /tmp/SOURCES/{$pkgname}-{$ver}/bin/
cp -rp $basedir/bin/lesskeeper-cli /tmp/SOURCES/{$pkgname}-{$ver}/bin/
cp -rp $basedir/bin/lesskeeper-store /tmp/SOURCES/{$pkgname}-{$ver}/bin/

cp -rp $basedir/misc/keeper/keeper.json /tmp/SOURCES/{$pkgname}-{$ver}/etc/keeper.json
cp -rp $basedir/misc/redis/redis.conf /tmp/SOURCES/{$pkgname}-{$ver}/etc/redis.conf

cp -rp $basedir/misc /tmp/SOURCES/{$pkgname}-{$ver}/misc

cd /tmp/SOURCES
tar zcf {$pkgname}-{$ver}.tar.gz {$pkgname}-{$ver}
";
shell_exec($cmd);

$os = "el6";

$file = "{$basedir}/misc/rhel/rpm.spec";
$spec = file_get_contents($file);

$mat = array(
    "/Name:\ +(.*?)\n/",
    "/Version:\ +(.*?)\n/",
    "/Release:\ +(.*?)\n/",
    "/Source0:\ +(.*?)\n/",
);
$rep = array(
    "Name: lesskeeper\n",
    "Version: {$ver}\n",
    "Release: {$rel}\n",
    "Source0: {$pkgname}-{$ver}.tar.gz\n",
);
$spec = preg_replace($mat, $rep, $spec);
$spec = str_replace('%{?dist}', '', $spec);
$spec = preg_replace("/Release:\ +(.*?)\n/", "Release: $1%{?dist}\n", $spec);

$specfile = "/tmp/{$pkgname}-{$ver}-rpm.spec";
file_put_contents($specfile, $spec);

$cmd = "rpmbuild -ba $specfile";
$cmd.= " --define='_tmppath /tmp'";
$cmd.= " --define='_builddir /tmp/BUILD'";
$cmd.= " --define='_topdir /tmp/'";
$cmd.= " --define='dist .{$os}'";

$retarr = array();
$retint = 0;
$retstr = exec($cmd, $retarr, $retint);
if ($retint > 0) {
    $_errstr = $cmd;
    foreach ($retarr as $v) {
        $_errstr .= "\n".$v;     
    }
}
shell_exec($cmd);

$cmd = "cp /tmp/RPMS/$arch/{$pkgname}-{$ver}*.rpm ~/";
shell_exec($cmd);

die(0);
